<!-- QQ授权后关联账号处理 -->
<template>
  <Form
    ref="target"
    class="xtx-form"
    :validation-schema="schema"
    autocomplete="off"
    v-slot="{ errors }"
  >
    <div class="user-info">
      <img :src="avatar" alt />
      <p>Hi，{{ nickname }} 欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</p>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field
          :class="{ err: errors.mobile }"
          name="mobile"
          v-model="form.mobile"
          class="input"
          type="text"
          placeholder="绑定的手机号"
        />
      </div>
      <div class="error" v-if="errors.mobile">
        <i class="iconfont icon-warning" />
        {{ errors.mobile }}
      </div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field
          :class="{ err: errors.code }"
          name="code"
          v-model="form.code"
          class="input"
          type="text"
          placeholder="短信验证码"
        />
        <span @click="send()" class="code">{{ timer <= 0 ? '发送验证码' : timer }}</span>
      </div>
      <div class="error" v-if="errors.code">
        <i class="iconfont icon-warning" />
        {{ errors.code }}
      </div>
    </div>
    <a href="javascript:;" @click="submit" class="submit">立即绑定</a>
  </Form>
</template>

<script>
import QC from 'qc'
import veeSchema from "@/utils/vee-validate-schema"
import Message from '@/components/library/Message'
import { reactive, ref } from 'vue'
import { Field, Form } from "vee-validate"
import { useIntervalFn } from "@vueuse/core"
import { userQQBindCode, userQQBindLogin } from "@/api/user"
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
export default {
  name: 'CallbackBind',
  props: {
    openId: {
      type: String,
      required: true
    }
  },
  setup(props) {
    // 2. 完成表单校验
    // 3. 发送验证吗（校验，定义api，调用，完成倒计时）
    // 4. 进行绑定（绑定成功就是登录成功）
    const nickname = ref(null)
    const avatar = ref(null)
    const form = reactive({
      mobile: null,
      code: null
    })

    // 1. 准备下信息：unionId(openId) qq头像 昵称
    if (QC.Login.check()) {
      QC.api('get_user_info').success(ret => {
        if (ret.status == 200) {
          nickname.value = ret.data.nickname
          avatar.value = ret.data.figureurl_1
        }
      })
    }

    // 表单验证规则
    const MySchema = {
      mobile: veeSchema.mobile,
      code: veeSchema.code,
    }


    /* ============ 短信验证码登录 ============== */
    const target = ref(null)
    const timer = ref(0)
    //pause 暂停 resume 重新开始 useIntervalFn(回调函数,执行间隔,是否立即开启)
    const { pause, resume } = useIntervalFn(() => {
      --timer.value
      if (timer.value <= 0) pause()
    }, 1000, false)
    // 发送验证码
    const send = async () => {
      //验证此信息返回验证结果信息
      const valid = MySchema.mobile(form.mobile)
      // 失败时,使用vee的错误函数显示错误信息 setFieldError(字段,错误信息)
      if (valid != true) return target.value.setFieldError('mobile', valid)
      // 没有倒计时才可以发送
      if (timer.value <= 0) {
        try {
          await userQQBindCode(form.mobile)
          Message({ type: 'success', text: '发送成功' })
          // 设置执行时长
          timer.value = 60
          resume()
        } catch (e) {
          console.dir(e);
          Message({ type: 'error', text: e.response.data.message || '发送失败' })
        }
      }
    }

    // 立即绑定
    const store = useStore()
    const router = useRouter()
    const submit = async () => {
      const valid = target.value.validate()
      if (valid) {

        userQQBindLogin({
          unionId: props.openId,
          ...form
        }).then(async data => {
          // 实现和之前登录一样的逻辑
          console.log(data);
          // 1. 存储用户信息
          const { id, account, avatar, mobile, nickname, token } = data.result
          store.commit('user/setUser', { id, account, avatar, mobile, nickname, token })
          // 合并本地购物车
          await store.dispatch('cart/mergeLocalCart')
          // 2. 跳转到来源页或者首页
          router.push(store.state.user.redirectUrl)
          // 3. 成功提示
          Message({ type: 'success', text: 'QQ绑定成功' })
        }).catch(e => {
          console.dir(e)
          if (e.response && e.response.data)
            return Message({ type: 'error', text: e.response.data.message })
          Message({ type: 'error', text: '绑定失败' })
        })
      }
    }


    return {
      nickname, avatar,
      form, schema: MySchema,
      target,
      send, timer,
      submit
    }
  },
  components: {
    Field, Form
  }
}
</script>

<style scoped lang='less'>
.user-info {
  width: 320px;
  height: 70px;
  margin: 0 auto;
  display: flex;
  background: #f2f2f2;
  align-items: center;
  padding: 0 10px;
  margin-bottom: 25px;
  img {
    background: #f2f2f2;
    width: 50px;
    height: 50px;
  }
  p {
    padding-left: 10px;
  }
}
.code {
  position: absolute;
  right: 5px;
  top: 1px;
  line-height: 48px;
  width: 100px;
  text-align: center;
  color: #999;
  background-color: white;
  padding: 0 10px;
  &:hover {
    cursor: pointer;
  }
}
</style>